﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using NExplorer.Controls;

namespace NExplorer.Controls
{
	internal class FileSystemListViewItem : ListViewItem
	{
		private const double c_kilobyte = 1024;
		private const double c_megabyte = c_kilobyte * c_kilobyte;
		private const double c_gigabyte = c_megabyte * c_kilobyte;

		private FileSystemInfo	_fileSystemInfo;
		private readonly bool	_isDirectory;
	
		public FileSystemListViewItem(FileSystemInfo path)
			: base(path.Name)
		{
			_fileSystemInfo = path;
			_isDirectory = path is DirectoryInfo;
		}

		public void Initialize(ImageList imageList)
		{
			SubItems.AddRange(new string[] { "", "", "", "" });
			
			Populate(imageList);
		}

		public void Refresh()
		{
			_fileSystemInfo.Refresh();

			Text = _fileSystemInfo.Name;
			Populate(ListView.SmallImageList);
		}

		public void Rename(FileSystemInfo fileSystemInfo)
		{
			_fileSystemInfo = fileSystemInfo;
			Refresh();
		}

		private void Populate(ImageList imageList)
		{
			string description;
			Icon icon;

			ServiceManager.FileOperations.GetIconAndDescription(_fileSystemInfo, out icon, out description);

			if (icon != null)
			{
				imageList.Images.Add(icon);
				ImageIndex = imageList.Images.Count - 1;
			}

			SubItems[2].Text = description;

			DateTime lastAccessTime;

			try
			{
				lastAccessTime = _fileSystemInfo.LastWriteTime.ToLocalTime();
			}
			catch
			{
				lastAccessTime = DateTime.MinValue;
			}

			SetSubItem(1, new ColumnItemData(string.Concat(lastAccessTime.ToShortDateString(), " ", lastAccessTime.ToShortTimeString()), lastAccessTime));

			if (IsDirectory)
			{
				SetSubItem(3, new ColumnItemData(""));
			}
			else 
			{
				long size = ((FileInfo)_fileSystemInfo).Length;
				string sizeString = GetSizeString(size);
				SetSubItem(3, new ColumnItemData(sizeString, size));
			}
		}

		public FileSystemInfo FileSystemInfo
		{
			get { return _fileSystemInfo; }	
		}

		public bool IsDirectory
		{
			get { return _isDirectory; }
		}

		private void SetSubItem(int index, ColumnItemData columnItemData)
		{
			SubItems[index] = new ExplorerListViewSubItem(this, columnItemData);
		}

		private static string GetSizeString(long size)
		{
			double dSize;
			string suffix;

			if (size > c_gigabyte)
			{
				dSize = (size / c_gigabyte);
				suffix = "GB";
			}
			else if (size > c_megabyte)
			{
				dSize = (size / c_megabyte);
				suffix = "MB";
			}
			else if (size > c_kilobyte)
			{
				dSize = (size / c_kilobyte);
				suffix = "KB";
			}
			else 
			{
				dSize = size;
				suffix = "B";
			}

			return string.Format("{0:n0} {1}", dSize, suffix);
		}
	}
}